package common

import (
	"context"
	"github.com/golang-jwt/jwt/v5"
	"strconv"
	"time"
)

// JwtCreate Generate jwt
func JwtCreate(jwtSecret string, expire int64, mallUserId string) (string, error) {
	t := time.Now().Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"bsu": mallUserId,
		"aud": mallUserId,
		"nbf": t,
		"iat": t,
		"exp": t + expire,
	})
	tokenString, err := token.SignedString([]byte(jwtSecret))
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// JwtAuthUserId - 获取当前用户id
func JwtAuthUserId(ctx context.Context) int64 {
	useId, err := strconv.ParseInt(ctx.Value("bsu").(string), 10, 32)
	if err != nil {
		return -1
	}
	return useId
}
